package cn.itcast.bassm.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.net.ssl.SSLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.itcast.bassm.mapper.PushMapper;
import cn.itcast.bassm.mapper.UserMapper;
import cn.itcast.bassm.pojo.Uploadfile;
import cn.itcast.bassm.service.InputandUpdowService;
import cn.itcast.bassm.service.QQMailService;

@Component
public class TaskCool {
	@Autowired
	private InputandUpdowService inputandUpdowService;
	@Autowired
	private QQMailService qQMailService;
	@Autowired
	private  PushMapper pushMapper;
	@Autowired
	private UserMapper userMapper;

	public void testJob() throws Throwable{
		try {
		/*//每天凌晨给访客刷新状态
		String yindate="0";

		Date data=new Date();

        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");

        String state = dateFormat.format(data);

        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        String yupdatetime = dateFormat2.format(data);
        
        userMapper.updatevistorsendtime(yupdatetime,state);*/
			
			inputandUpdowService.getUser();//拉取数据

	} catch (Exception e) {	

		e.printStackTrace();

	}
		
		


	
/*String txtPath ="/home/apache-tomcat-8.0.24/webapps/MailBox.txt";  //发邮箱

	String QQZhangHao=ReadMailBox.readTxtLine(txtPath, 5);

	String url=QQZhangHao+"/api/v1/alarm/query";

	String msg1=qQMailService.Acquisitiontime(url);

	System.out.println(msg1);*/
	/*String msg =inputandUpdowService.finsclecttestone();

	System.out.println(msg);*/
		}
	
	//更新用户更换了图片之后，两天检测一次，更换标记
	public void testJobtow() throws ParseException{
		String examine ="3";
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date data=new Date();
        String nowtime = df.format(data);
		List<Uploadfile> listuser= userMapper.selcettoUploadfileandexamine(examine);
		if(listuser.size()==0){
			//没有设备导入失败的用户
			System.out.println("没有设备导入失败的数据");
		}else {
			for (int i = 0; i < listuser.size(); i++) {
				String timeto=listuser.get(i).getUpdatetime();
				int idto = listuser.get(i).getYid();
				String yid = String.valueOf(idto);
				Date d1 = df.parse(timeto);
				Date d2 = df.parse(nowtime);
				long diff = d2.getTime() - d1.getTime();
				long days = (1000 * 60 * 60 * 24 * 2);
				if(diff>days){
					//用户图片更换超过了2天，更新用户标识
					String examineto = "1";
					userMapper.uptoUploadfileandexamine(examineto, nowtime,yid);
					System.out.println("大于两天");
				}else {
					//用户图片更换小于两天不做操作
					System.out.println("小于两天");
				}
			}
		}
		
	}
	
	
	/**
	 * 每天测试接口  
	 * @throws UnsupportedEncodingException 
	 */
	public void testJob2() throws UnsupportedEncodingException{
		
		String httpUrl = "http://imlaixin.cn/Api/send/data/json";

		String mm="接口出现异常请处理【E安全服务器】";
		String httpArgto = "accesskey=1861&secretkey=c2d829b888f73073de0af3f6653d23c7ae8ec2c9&mobile=15019389227&content=";
		
		//SSM项目
		String xintiao="https://wwl.ycws.cc/ssm/v1/wwlcommunication";//心跳接口
		String laqushuju="https://wwl.ycws.cc/ssm/v1/wwluserinfo";//拉取数据接口
		String shibaibaocuo="https://wwl.ycws.cc/ssm/v1/wwlcount";//统计开门次数
		String kaimenjilu="https://wwl.ycws.cc/ssm/v1/wwlfail";	//失败记录
		String xcxfaceurl="http://api-cn.faceplusplus.com/facepp/v3/detect";//face++检测图片地址
		
		//彩之云接口
		String czykahaochaxun="https://wwl.ycws.cc/h5/card/selectCard";//查询卡号接口
		String czykahaogoumai="https://wwl.ycws.cc/h5/card/buy";//卡号购买
		String czyhuxusuoyouxiaoqu="https://wwl.ycws.cc/h5/l/showAll";//获取所有小区
		String czyhuqusuoyouloudong="https://wwl.ycws.cc/h5/l/showUnit";//获取所有楼栋
		String czychaxunopenid="https://wwl.ycws.cc/h5/u/doesitExist";//查询openid
		
		//小程序
		String wxpayurl="https://wwl.ycws.cc/ssm/owner/selectOnePhone";//查询业主openid表显示
		String fkwxpayurl="https://wwl.ycws.cc/ssm/visitors/openid";//查询访客表显示
		String wxpadyurluser="https://wwl.ycws.cc/ssm/owner/newselectPhone";//查询业主的信息
		
		
		String idnumber="009bf165301a5d67";//彩悦大厦8楼	
		String n="1";
		String m="0";
		String d="100";//异常参数
		
		Date data2=new Date();
        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timetwo = dateFormat2.format(data2);
		

       // ------------------------------------------------------------------------------------------------调用心跳接口
		String result1;
		result1 = doPostSelect(xintiao,idnumber);
		String mto1="心跳接口"+mm;
		String mto=bmzh(mto1);
		if(result1.equals(d)){//接口调用失败
			
			String httpArg1=httpArgto+mto;
			String jsonResultxintiao = request(httpUrl, httpArg1);
			System.out.println("失败-心跳接口" +jsonResultxintiao);
		}else {//接口调用成功
			JsonParser parser = new JsonParser(); // 创建JSON解析器
	        JsonObject object = (JsonObject) parser.parse(result1); // 创建JsonObject对象
	        String index1=object.get("state").getAsString();
			if(index1.equals(n)||index1.equals(m)){
				//成功不做操作
				System.out.println("成功-调用心跳接口");
			}else {
				
				String httpArg1=httpArgto+mto+mm;
				String jsonResultxintiao = request(httpUrl, httpArg1);
				System.out.println("失败-心跳接口" +jsonResultxintiao);
			}
		}
		
		//------------------------------------------------------------------------------------------------调用拉取数据接口

			
		Date data=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd 01:01:01");
        String updatetime = dateFormat.format(data);
		String starttime=updatetime;
		String result2 = doPostSelect2(laqushuju,idnumber,starttime);
		String mto2="调用拉取数据接口"+mm;
		String mto2to=bmzh(mto2);
		String httpArg2=httpArgto+mto2to;
        if(result2.equals(d)){
        	
			
			String jsonResultlashuju = request(httpUrl, httpArg2);
			System.out.println("失败-调用拉取数据接口"+jsonResultlashuju);
        }else {
        	JsonParser parser2 = new JsonParser(); // 创建JSON解析器
            JsonObject object2 = (JsonObject) parser2.parse(result2); // 创建JsonObject对象
            JsonArray index2= object2.getAsJsonArray("list");
			if(index2==null){
			

				String jsonResultlashuju = request(httpUrl, httpArg2);
				System.out.println("失败-调用拉取数据接口"+jsonResultlashuju);

			}else {
				//成功
				System.out.println("成功-调用拉取数据接口");


			}
		}
        
        //------------------------------------------------------------------------------------------------调用开门记录
        Date data3=new Date();
        SimpleDateFormat dateFormat3=new SimpleDateFormat("yyyy-MM-dd 01:01:01");
        String updatetime3 = dateFormat3.format(data3);
		String datetime=updatetime3;
		String doortype="Face";
		String usertyped="0";
		String result3 = doPostSelect3(shibaibaocuo,idnumber,datetime,doortype,usertyped);
		String mto3="调用开门记录"+mm;
		String mto3to=bmzh(mto3);
		String httpArg3=httpArgto+mto3to;
		if(result3.equals(d)){//接口调用失败
			
			
			String jsonResultkaimen = request(httpUrl, httpArg3);
			System.out.println("失败-调用开门记录"+jsonResultkaimen);
		}else {//接口调用成功
			JsonParser parser3 = new JsonParser(); // 创建JSON解析器
	        JsonObject object3 = (JsonObject) parser3.parse(result3); // 创建JsonObject对象
			String index3=object3.get("state").getAsString();
			if(index3.equals(n)||index3.equals(m)){
				//成功
				System.out.println("成功-调用开门记录");
			}else {
				
			
				String jsonResultkaimen = request(httpUrl, httpArg3);
				System.out.println("失败-调用开门记录"+jsonResultkaimen);
			}
		}
        
        
       // ------------------------------------------------------------------------------------------------调用PAD数据导入错误
			/*Date data4=new Date();
	        SimpleDateFormat dateFormat4=new SimpleDateFormat("yyyy-MM-dd 01:01:01");
	        String updatetime4 = dateFormat4.format(data4);
			String datetime4=updatetime4;
			String pad=idnumber;
			String failtype="-6";
			String usertype="0";
			String result4 = doPostSelect4(kaimenjilu,pad,failtype,usertype);
			JsonParser parser4 = new JsonParser(); // 创建JSON解析器
	        JsonObject object4 = (JsonObject) parser4.parse(result4); // 创建JsonObject对象
			String index4=object4.get("state").getAsString();
			if(result4.equals(d)){//接口调用失败
				//把结果插入进数据库
				mto="调用PAD数据导入错误";
				String jsonResult = request(httpUrl, httpArg);
			}else {//接口调用成功
				if(index4.equals(n)||index4.equals(m)){
					//成功
					System.out.println("成功");
				}else {
					mto="调用PAD数据导入错误";
					String jsonResult = request(httpUrl, httpArg);
					
				}
			}*/
		//-----------------------------------------------------------------------------------------------------彩之云查询卡号接口
			String cardnumber="0655615749";
			String community_name="花样年.花好园";
			String urlto=czykahaochaxun+"?"+"cardnumber="+cardnumber+"&"+"community_name="+community_name;
			String result5 =dogetSwlectlian(urlto);
			String mto4="彩之云查询卡号接口"+mm;
			String mto4to=bmzh(mto4);
			String httpArg4=httpArgto+mto4to;
			if(result5.equals(d)){//接口调用失败
				//把结果插入进数据库
				
				String jsonResultchaxunlahao = request(httpUrl, httpArg4);
				System.out.println("失败-彩之云查询卡号接口"+jsonResultchaxunlahao);
			}else {//接口调用成功
				JsonParser parser5 = new JsonParser(); // 创建JSON解析器
		        JsonObject object5 = (JsonObject) parser5.parse(result5); // 创建JsonObject对象
				String index5=object5.get("code").getAsString();
				if(index5.equals("0")){
					//成功
					System.out.println("成功-彩之云查询卡号接口");
				}else {

					String jsonResultchaxunlahao = request(httpUrl, httpArg4);
					System.out.println("失败-彩之云查询卡号接口"+jsonResultchaxunlahao);
					
				}
			}
		//-------------------------------------------------------------------------------------------------------卡号购买统一下单接口
			String moblie="f0b148b8769b2b35430a2ee781fbb491";
			String yphone="13652361631";
			String Yid="17547";
			String urlto1=czykahaogoumai+"?"+"moblie="+moblie+"&"+"yphone="+yphone+"&"+"Yid="+Yid;
			String result6 =dogetSwlectlian(urlto1);
			String mto5="彩之云卡号购买统一下单接口"+mm;
			String mto5to=bmzh(mto5);
			String httpArg5=httpArgto+mto5to;
			if(result6.equals(d)){//接口调用失败
				
				String jsonResultxiadan = request(httpUrl, httpArg5);
				System.out.println("失败-卡号购买统一下单接口"+jsonResultxiadan);
			}else {//接口调用成功
				JsonParser parser6 = new JsonParser(); // 创建JSON解析器
		        JsonObject object6 = (JsonObject) parser6.parse(result6); // 创建JsonObject对象
				String index6=object6.get("code").getAsString();
				if(index6.equals("0")){
					//成功
					System.out.println("成功-卡号购买统一下单接口");
				}else {
					String jsonResultxiadan = request(httpUrl, httpArg5);
					System.out.println("失败-卡号购买统一下单接口"+jsonResultxiadan);
				}
			}
		//-----------------------------------------------------------------------------------------------------------获取所有小区信息 7
			
			
			String urlto2=czyhuxusuoyouxiaoqu;
			String result7 =dogetSwlectlian(urlto2);
			String mto6="获取所有小区信息"+mm;
			String mto6to=bmzh(mto6);
			String httpArg6=httpArgto+mto6to;
			if(result7.equals(d)){//接口调用失败
				//把结果插入进数据库
				
				String jsonResultxiaoqu = request(httpUrl, httpArg6);
				System.out.println("失败-获取所有小区信息"+jsonResultxiaoqu);
			}else {//接口调用成功
				JsonParser parser7 = new JsonParser(); // 创建JSON解析器
		        JsonObject object7 = (JsonObject) parser7.parse(result7); // 创建JsonObject对象
				String index7=object7.get("code").getAsString();
				if(index7.equals("0")){
					//成功
					System.out.println("成功-获取所有小区信息");
				}else {
					
					String jsonResultxiaoqu = request(httpUrl, httpArg6);
					System.out.println("失败-获取所有小区信息"+jsonResultxiaoqu);
				}
			}
			
		//-----------------------------------------------------------------------------------------------------------获取指定小区对应楼栋信息 8
			
			String address="逸景蓝湾";
			String urlto3=czyhuqusuoyouloudong+"?"+"address="+address;
			String result8 =dogetSwlectlian(urlto3);
			String mto7="获取指定小区对应楼栋信息"+mm;
			String mto7to=bmzh(mto7);
			String httpArg7=httpArgto+mto7to;
			if(result8.equals(d)){//接口调用失败
				//把结果插入进数据库
				
				String jsonResultliudong = request(httpUrl, httpArg7);
				System.out.println("失败-获取指定小区对应楼栋信息"+jsonResultliudong);
			}else {//接口调用成功
				JsonParser parser8 = new JsonParser(); // 创建JSON解析器
		        JsonObject object8 = (JsonObject) parser8.parse(result8); // 创建JsonObject对象
				String index8=object8.get("code").getAsString();
				if(index8.equals("0")){
					//成功
					System.out.println("成功-获取指定小区对应楼栋信息");
				}else {
					
					String jsonResultliudong = request(httpUrl, httpArg7);
					System.out.println("失败-获取指定小区对应楼栋信息"+jsonResultliudong);
				}
			}
			
	
	
	//-----------------------------------------------------------------------------------------------------------查询彩之云openid是否存在 9
	String Userid="a26cca8519f2e02be5b64000c25f1ec2";
	String urlto4=czychaxunopenid+"?"+"Userid="+Userid;
	String result9 =dogetSwlectlian(urlto4);
	String mto8="查询彩之云openid是否存在"+mm;
	String mto8to=bmzh(mto8);
	String httpArg8=httpArgto+mto8to;
	if(result9.equals(d)){//接口调用失败
		//把结果插入进数据库
		
		String jsonResultopenid = request(httpUrl, httpArg8);
		System.out.println("失败-查询彩之云openid是否存在"+jsonResultopenid);
	}else {//接口调用成功
		JsonParser parser9 = new JsonParser(); // 创建JSON解析器
	    JsonObject object9 = (JsonObject) parser9.parse(result9); // 创建JsonObject对象
		String index9=object9.get("code").getAsString();
		if(index9.equals("0")||index9.equals("1")){
			//成功
			System.out.println("成功-查询彩之云openid是否存在");
		}else {
			
			String jsonResultopenid = request(httpUrl, httpArg8);
			System.out.println("失败-查询彩之云openid是否存在"+jsonResultopenid);
			
		}
	}
	
	//------------------------------------------------------------------------------------------------------------旷视
	 
	 
	File file = new File("E:\\桌面\\微信图片_20171118150544.jpg");
	byte[] buff = getBytesFromFile(file);
	String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
    HashMap<String, String> map = new HashMap();
    HashMap<String, byte[]> byteMap = new HashMap();
    map.put("api_key", "mDyC2jSC_Mlpp8ZU9vp7VL5olqO4tsWl");
    map.put("api_secret", "7L5mhuPM7KYUYCb0vb-WnN-F6dLzc5Jx");
    byteMap.put("image_file", buff);
    String mto9 ="矿视"+mm;
    String mto9to=bmzh(mto9);
    String httpArg9=httpArgto+mto9to;
    byte[] facebyte;
	try {
		facebyte = post(url, map, byteMap);
		if(facebyte.length==0){
			//失败
			String jsonResultopenid = request(httpUrl, httpArg9);
			System.out.println("失败-查询彩之云openid是否存在"+jsonResultopenid);
		}else {
			//成功
			System.out.println("矿视成功");
		}
		String str = new String(facebyte);
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	//------------------------------------------------------------------------------------------------------------小程序查询业主openid数据
	String yphoneto="13923990660";
	List<NameValuePair> params10 = new ArrayList<NameValuePair>();
	params10.add(new BasicNameValuePair("yphone",yphoneto));
	String result10=doPostSelectlian(wxpayurl,params10);
	String mto10="小程序查询业主openid数据"+mm;
	String mto10to=bmzh(mto10);
	String httpArg10=httpArgto+mto10to;
	if(result10.equals(d)){
		//失败
		String jsonResultopenid = request(httpUrl, httpArg10);
		System.out.println("失败-小程序查询业主openid数据"+jsonResultopenid);
	}else {
		//成功
		System.out.println("成功-小程序查询业主openid数据");
	}
	
	
	//------------------------------------------------------------------------------------------------------------小程序查询访客数据
	String openidmm="oV3MK0bCJDKuE0RlkgmDkjP9astM";
	List<NameValuePair> params11 = new ArrayList<NameValuePair>();
	params11.add(new BasicNameValuePair("openid",openidmm));
	String result11=doPostSelectlian(fkwxpayurl,params11);
	String mto11="小程序查询访客数据"+mm;
	String mto11to=bmzh(mto11);
	String httpArg11=httpArgto+mto11to;
	if(result11.equals(d)){
		//失败
		String jsonResultopenid = request(httpUrl, httpArg11);
		System.out.println("失败-小程序查询访客数据"+jsonResultopenid);
	}else {
		//成功
		System.out.println("成功-小程序查询访客数据");
	}
	
	//------------------------------------------------------------------------------------------------------------小程序查询业主数据
	
	List<NameValuePair> params12 = new ArrayList<NameValuePair>();
	String yh="15019689887";
	params12.add(new BasicNameValuePair("yphone",yh));
	String result12=doPostSelectlian(wxpadyurluser,params12);
	String mto12="小程序查询业主数据"+mm;
	String mto12to=bmzh(mto12);
	String httpArg12=httpArgto+mto12to;
	if(result10.equals(d)){
		//失败
		String jsonResultopenid = request(httpUrl, httpArg12);
		System.out.println("失败-小程序查询业主数据"+jsonResultopenid);
	}else {
		//成功
		
		System.out.println("成功-小程序查询业主数据");
	}
	
	
	}
    
	

public static String doPostSelect(String urlStr,String idnumber) {
    String result = null;
    HttpPost httpPost = new HttpPost(urlStr);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("idnumber",idnumber));

    try {

    	HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
        httpPost.setEntity(entity);// 设置参数实体
        @SuppressWarnings("resource")
        HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
        HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
        if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
        } else {
            result="100";
        }
    } catch (ConnectTimeoutException e) {
    	result="100";
    } catch (UnsupportedEncodingException e) {
    	result="100";
    } catch (IOException e) {
    	result="100";
    } catch (Exception e) {
    	result="100";
    }

    return result;
}


public static String doPostSelect2(String urlStr,String idnumber,String starttime) {
    String result = null;
    HttpPost httpPost = new HttpPost(urlStr);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("idnumber",idnumber));
	params.add(new BasicNameValuePair("starttime",starttime));

    try {

    	HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
        httpPost.setEntity(entity);// 设置参数实体
        @SuppressWarnings("resource")
        HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
        HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
        if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
        } else {
            result="100";
        }
    } catch (ConnectTimeoutException e) {
    	result="100";
    } catch (UnsupportedEncodingException e) {
    	result="100";
    } catch (IOException e) {
    	result="100";
    } catch (Exception e) {
    	result="100";
    }

    return result;
}


public static String doPostSelect3(String urlStr,String idnumber,String datetime,String doortype,String usertyped) {
    String result = null;
    HttpPost httpPost = new HttpPost(urlStr);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("id","1"));
	params.add(new BasicNameValuePair("idnumber",idnumber));
	params.add(new BasicNameValuePair("datetime",datetime));
	params.add(new BasicNameValuePair("doortype",doortype));
	params.add(new BasicNameValuePair("usertype",usertyped));
    try {

    	HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
        httpPost.setEntity(entity);// 设置参数实体
        @SuppressWarnings("resource")
        HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
        HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
        if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
        } else {
            result="100";
        }
    } catch (ConnectTimeoutException e) {
    	result="100";
    } catch (UnsupportedEncodingException e) {
    	result="100";
    } catch (IOException e) {
    	result="100";
    } catch (Exception e) {
    	result="100";
    }

    return result;
}


public static String doPostSelect4(String urlStr,String pad,String failtype,String usertype) {
    String result = null;
    HttpPost httpPost = new HttpPost(urlStr);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("id","1"));
	params.add(new BasicNameValuePair("pad",pad));
	params.add(new BasicNameValuePair("failtype",failtype));
	params.add(new BasicNameValuePair("usertype",usertype));

    try {

    	HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
        httpPost.setEntity(entity);// 设置参数实体
        @SuppressWarnings("resource")
        HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
        HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
        if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
        } else {
            result="100";
        }
    } catch (ConnectTimeoutException e) {
    	result="100";
    } catch (UnsupportedEncodingException e) {
    	result="100";
    } catch (IOException e) {
    	result="100";
    } catch (Exception e) {
    	result="100";
    }

    return result;
}
	



	/**
	 * @param urlAll
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 * 调用短信，发送给指定手机
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");       
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	
	/**
	 * httpclen post 方法
	 */
    public static String doPostSelectlian(String urlStr,List<NameValuePair>params) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);
        try {

        	HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
            httpPost.setEntity(entity);// 设置参数实体
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                result="100";
            }
        } catch (ConnectTimeoutException e) {
        	result="100";
        } catch (UnsupportedEncodingException e) {
        	result="100";
        } catch (IOException e) {
        	result="100";
        } catch (Exception e) {
        	result="100";
        }

        return result;
    }
    
    /**
     * httpclen get 请求
     */
    
    public static String dogetSwlectlian(String urlStr){
    	String result = null;
        //HttpDelete httpDelete = new HttpDelete(urlStr);
        HttpGet httpGet = new HttpGet(urlStr);

        try {

           // HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集-8");
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpGet);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
            	result="100";
            }
        } catch (ConnectTimeoutException e) {
        	result="100";
        } catch (UnsupportedEncodingException e) {
        	result="100";
        } catch (IOException e) {
        	result="100";
        } catch (Exception e) {
        	result="100";
        }

        return result;
    }
    
    /**
     *  编码装换
     * @throws UnsupportedEncodingException 

     */
    
    public static String bmzh(String namemsg) throws UnsupportedEncodingException {
			String usernamemsg=URLEncoder.encode(namemsg, "UTF-8");
			return usernamemsg;
		
    }
    
    
    /**
     * 旷视 
     */
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();
    protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if(fileMap != null && fileMap.size() > 0){
            Iterator fileIter = fileMap.entrySet().iterator();
            while(fileIter.hasNext()){
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try{
            if(code == 200){
                ins = conne.getInputStream();
            }else{
                ins = conne.getErrorStream();
            }
        }catch (SSLException e){
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while((len = ins.read(buff)) != -1){
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }
    
    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }
    private static String encode(String value) throws Exception{
        return URLEncoder.encode(value, "UTF-8");
    }
    
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }
}



